#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
调试排列5预测结果为空的问题
"""

import sys
import os
import torch
import numpy as np
from PyQt5.QtWidgets import QApplication

# 添加项目根目录到路径
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)

def debug_plw_prediction_issue():
    """调试排列5预测结果为空的问题"""
    print(" 调试排列5预测结果为空的问题")
    print("=" * 60)
    
    try:
        from lottery_predictor_app import LotteryPredictorApp
        from algorithms.plw_sequence_lstm import PLWDataProcessor
        
        # 创建应用
        if not QApplication.instance():
            app = QApplication(sys.argv)
        
        predictor = LotteryPredictorApp()
        
        print("📋 步骤1: 检查模型文件...")
        try:
            plw_model_path = os.path.join(project_root, 'scripts', 'plw', 'plw_model.pth')
            print(f"   模型文件路径: {plw_model_path}")
            print(f"   文件存在: {os.path.exists(plw_model_path)}")
            if os.path.exists(plw_model_path):
                print(f"   文件大小: {os.path.getsize(plw_model_path) / (1024*1024):.2f} MB")
        except Exception as e:
            print(f"[ERROR] 模型文件检查失败: {e}")
        
        print("\n📋 步骤2: 检查数据文件...")
        try:
            plw_data_file = os.path.join(project_root, 'scripts', 'plw', 'plw_history.csv')
            print(f"   数据文件路径: {plw_data_file}")
            print(f"   文件存在: {os.path.exists(plw_data_file)}")
            if os.path.exists(plw_data_file):
                print(f"   文件大小: {os.path.getsize(plw_data_file) / (1024*1024):.2f} MB")
        except Exception as e:
            print(f"[ERROR] 数据文件检查失败: {e}")
        
        print("\n📋 步骤3: 测试数据处理器...")
        try:
            processor = PLWDataProcessor(plw_data_file, window_size=10)
            recent_data = processor.get_recent_data()
            print(f"[INFO] 数据处理器测试成功")
            print(f"   最近数据形状: {recent_data.shape if recent_data is not None else 'None'}")
            if recent_data is not None:
                print(f"   数据类型: {type(recent_data)}")
                print(f"   数据示例: {recent_data[0, -1, :5].tolist()}")  # 显示最后时间步的5个数字
        except Exception as e:
            print(f"[ERROR] 数据处理器测试失败: {e}")
            import traceback
            traceback.print_exc()
            return False
        
        print("\n📋 步骤4: 测试模型加载...")
        try:
            plw_model, _, scaler_X = predictor.load_models_with_cache("plw")
            print(f"[INFO] 模型加载成功")
            print(f"   模型类型: {type(plw_model)}")
            if hasattr(plw_model, 'lstm'):
                print(f"   LSTM输入维度: {plw_model.lstm.input_size}")
                print(f"   LSTM隐藏维度: {plw_model.lstm.hidden_size}")
        except Exception as e:
            print(f"[ERROR] 模型加载失败: {e}")
            import traceback
            traceback.print_exc()
            return False
        
        print("\n📋 步骤5: 测试LSTM-CRF预测...")
        try:
            predictions = predictor.get_lstm_crf_predictions("plw", 1)
            print(f"[INFO] LSTM-CRF预测完成")
            print(f"   预测结果数量: {len(predictions)}")
            for i, pred in enumerate(predictions):
                print(f"   第{i+1}组: {pred}")
        except Exception as e:
            print(f"[ERROR] LSTM-CRF预测失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
        print("\n📋 步骤6: 测试序列LSTM增强模式预测...")
        try:
            predictions = predictor.get_enhanced_lstm_predictions("plw", 1)
            print(f"[INFO] 序列LSTM增强模式预测完成")
            print(f"   预测结果数量: {len(predictions)}")
            for i, pred in enumerate(predictions):
                print(f"   第{i+1}组: {pred}")
        except Exception as e:
            print(f"[ERROR] 序列LSTM增强模式预测失败: {e}")
            import traceback
            traceback.print_exc()
            return False
        
        return True
        
    except Exception as e:
        print(f"[ERROR] 调试失败: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = debug_plw_prediction_issue()
    if success:
        print("\n[INFO] 调试完成！")
    else:
        print("\n[ERROR] 调试失败！")